package com.itheima.controller;

import cn.hutool.core.collection.CollUtil;
import com.itheima.domain.PmsProductAttribute;
import com.itheima.domain.PmsProductAttributeCategory;
import com.itheima.exception.BusinessException;
import com.itheima.service.db.PmsProductAttributeCategoryService;
import com.itheima.service.db.PmsProductAttributeService;
import com.itheima.util.R;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/productAttribute/category")
public class PmsProductAttributeCategoryController {
    @DubboReference
    PmsProductAttributeCategoryService ppacService;
    @DubboReference
    PmsProductAttributeService ppaService;

    //获取所有商品属性分类及其下属性
    @GetMapping("/list/withAttr")
    public R withAttr() {
        List<PmsProductAttributeCategory> list = ppacService.findAll();
        if (CollUtil.isNotEmpty(list)) {
            for (PmsProductAttributeCategory ppac : list) {
                List<PmsProductAttribute> ppas = ppaService.findByPpacId(ppac.getId());
                ppac.setProductAttributeList(ppas);
            }
        }
        return R.success(list);
    }

    //分页获取所有商品属性分类
    @GetMapping("/list")
    public R findByPage(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        return R.success(ppacService.findByPage(pageNum, pageSize));
    }

    //添加商品属性分类
    @PostMapping("/create")
    public R create(@RequestParam String name) {
        PmsProductAttributeCategory ppac = new PmsProductAttributeCategory();
        ppac.setName(name);
        ppac.setAttributeCount(0);
        ppac.setParamCount(0);
        ppacService.save(ppac);
        return R.success("");
    }

    //修改商品属性分类
    @PostMapping("/update/{id}")
    public R update(@PathVariable Long id, @RequestParam String name) {
        ppacService.update(id, name);
        return R.success("");
    }

    //获取单个商品属性分类信息
    @GetMapping("{id}")
    public R findById(@PathVariable Long id) {
        return R.success(ppacService.findById(id));
    }

    //删除单个商品属性分类
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable Long id) {
        //查询类型下是否还含有属性和参数
        List<PmsProductAttribute> byPpacId = ppaService.findByPpacId(id);
        if (byPpacId == null || byPpacId.size() == 0) {
            ppacService.delete(id);
            return R.success("删除成功");
        } else {
            throw new BusinessException("该类型下仍包含属性");
        }
    }
}
